package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.device.phone.PhoneNettyTcpServerHandler;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.domain.DmcDeviceOnlineRecord;
import com.csun.cmny.provider.model.dto.device.DmcEditDeviceDto;
import com.csun.cmny.provider.model.dto.phone.BindPhoneLocationDto;
import com.csun.cmny.provider.model.dto.phone.PhonePageQuery;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.enums.phone.DmcPhoneLocationBindTypeEnum;
import com.csun.cmny.provider.model.vo.DmcPhoneVo;
import com.csun.cmny.provider.model.vo.RoomBuildingVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.DmcDeviceOnlineRecordService;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.provider.service.DmcPhoneLocationService;
import com.csun.cmny.provider.validator.DmcDeviceEditValidator;
import com.csun.cmny.util.PubUtils;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-08 11:32
 * @Description: the class dmc device phone controller
 */
@RestController
@RequestMapping(value = "/phone", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcPhoneMainController extends BaseController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private DmcPhoneLocationService dmcPhoneLocationService;
    @Resource
    private PhoneNettyTcpServerHandler phoneNettyTcpServerHandler;
    @Resource
    private DmcDeviceOnlineRecordService dmcDeviceOnlineRecordService;

    /**
     * 查询组织电话机设备列表
     *
     * @param phonePageQuery   the phone page query
     *
     * @return  the wrapper
     */
    @ApiOperation(httpMethod = "POST", value = "查询组织电话机设备列表")
    @RequestMapping(value = "/queryGroupPhoneListWithPage", method = RequestMethod.POST)
    public Wrapper queryGroupPhoneListWithPage(@RequestBody PhonePageQuery phonePageQuery) {

        phonePageQuery.setGroupId(getLoginAuthDto().getGroupId());
        phonePageQuery.setDeviceType(DmcDeviceTypeEnum.ZN_PHONE.getIndex());

        PageInfo pageInfo = dmcPhoneLocationService.queryPhoneListWithPage(phonePageQuery);
        for (Object o : pageInfo.getList()) {
            DmcPhoneVo dmcPhoneVo = (DmcPhoneVo) o;
            if (!PubUtils.isNull(dmcPhoneVo.getBindType())) {
                dmcPhoneVo.setBind(true);
                if (dmcPhoneVo.getBindType().equals(DmcPhoneLocationBindTypeEnum.ROOM.getKey())) {
                    RoomBuildingVo rbv = (RoomBuildingVo) redisTemplate
                            .opsForValue().get(RedisKeyUtil.getOmcRoomId(dmcPhoneVo.getRoomId()));
                    if (PublicUtil.isNotEmpty(rbv)) {
                        dmcPhoneVo.setLocation(rbv.getLocation());
                    }

                }
            }
        }

      //  return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * 添加电话机设备
     *
     * @param dmcEditDeviceDto  the dmc edit device dto
     * @param br                the binding result
     *
     * @return  the wrapper
     */
    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "添加电话机设备")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Wrapper addPhoneDevice(@Validated @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();

        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.ZN_PHONE.getIndex());

        Integer result = dmcDeviceService.addDevice(dmcDevice, getLoginAuthDto());

      //  return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 修改电话机设备
     *
     * @param dmcEditDeviceDto  the dmc edit device dto
     * @param br                the binding result
     *
     * @return  the wrapper
     */
    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "修改电话机设备")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Wrapper editPhoneDevice(@Validated(value = {DmcDeviceEditValidator.class})
                                   @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();
        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.ZN_PHONE.getIndex());

        Integer result = dmcDeviceService.editDevice(dmcDevice, getLoginAuthDto());

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 根据Id删除智能电话机
     *
     * @param id    the id
     *
     * @return  the wrapper
     */
    @ApiOperation(httpMethod = "POST", value = "根据Id删除智能电话机")
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.POST)
    public Wrapper deleteDmcPhoneById(@PathVariable Long id) {

        DmcDevice dmcDevice = dmcDeviceService.selectByKey(id);

        Integer result = dmcPhoneLocationService.deletePhoneById(id);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 断开netty连接
            phoneNettyTcpServerHandler.channelCloseByDeviceNo(dmcDevice.getDeviceNo());

            // 清除redisKey
            redisTemplate.delete(RedisKeyUtil.getZnPhoneKey(dmcDevice.getDeviceNo()));
            //删除设备在离线日志
            DmcDeviceOnlineRecord dmcDeviceOnlineRecord = new DmcDeviceOnlineRecord();
            dmcDeviceOnlineRecord.setDeviceId(id);
            int delete = dmcDeviceOnlineRecordService.delete(dmcDeviceOnlineRecord);
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 绑定智能电话机
     *
     * @param bindPhoneLocationDto bind phone location dto
     *
     * @return the wrapper.
     */
    @ValidateAnnotation
//    @LogAnnotation(isSaveResponseData = true, isSaveRequestData = true)
    @RequestMapping(value = "/bindPhoneLocation", method = RequestMethod.POST)
    public Wrapper bindPhoneLocation(@Validated @RequestBody BindPhoneLocationDto bindPhoneLocationDto,
                                     BindingResult br) {

        Integer result = dmcPhoneLocationService.bindPhoneLocation(bindPhoneLocationDto);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

      //  return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 解绑智能电话机
     *
     * @param deviceId  device id
     *
     * @return  the wrapper.
     */
//    @LogAnnotation(isSaveResponseData = true, isSaveRequestData = true)
    @RequestMapping(value = "/breakPhoneLocation/{deviceId}", method = RequestMethod.POST)
    public Wrapper breakPhoneLocation(@PathVariable Long deviceId) {

        Integer result = dmcPhoneLocationService.breakPhoneLocation(deviceId);
        //删除设备在离线日志
        DmcDeviceOnlineRecord dmcDeviceOnlineRecord = new DmcDeviceOnlineRecord();
        dmcDeviceOnlineRecord.setDeviceId(deviceId);
        int delete = dmcDeviceOnlineRecordService.delete(dmcDeviceOnlineRecord);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

      //  return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

}
